import request from "@/utils/request";
import { BASE_URL } from "@/settings";

const state = {
  depSource: [],
  posSource: [],
  depMap: {},
  posMap: {}
};

const mutations = {
  updateDepSource: (state, data) => {
    if (data.length > 0) {
      const topItem = data.filter(item => item.isTop)[0];
      const depTree = buildIterTree(data, topItem.parentId);
      state.depSource = depTree[0].children || [];

      const depMapTemp = {};
      for (let i = 0; i < data.length; i++) {
        depMapTemp[data[i].id] = data[i];
      }
      state.depMap = depMapTemp;
    } else {
      state.depSource = [];
      state.depMap = {};
    }
  },
  updatePosSource: (state, data) => {
    if (data.length > 0) {
      const posTree = buildIterTree(data, "0", true);
      posTree[0].disabled = true;
      state.posSource = posTree[0].children || [];

      const posMapTemp = {};
      for (let i = 0; i < data.length; i++) {
        posMapTemp[data[i].id] = data[i];
      }
      state.posMap = posMapTemp;
    } else {
      state.posSource = [];
      state.posMap = {};
    }
  }
};

const actions = {
  loadDepSourceAct: ({ commit }, companyId) => {
    request({
      url: `${BASE_URL}/hr/api/v1/depInfos/listAll?companyId=${companyId}`
    })
      .then(res => {
        commit("updateDepSource", res);
      })
      .catch(err => {
        console.log("loadDepSourceAct", err);
      });
  },
  loadPosSourceAct: ({ commit }, companyId) => {
    request({
      url: `${BASE_URL}/hr/api/v1/positionInfos/listAll?companyId=${companyId}`
    })
      .then(res => {
        commit("updatePosSource", res);
      })
      .catch(err => {
        console.log("loadPosSourceAct", err);
      });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};

function buildIterTree(data, parentId, isPos) {
  const result = [];
  let temp = null;
  for (let i = 0; i < data.length; i++) {
    if (data[i].parentId === parentId) {
      const obj = {
        value: data[i]["id"],
        key: data[i]["id"],
        label: data[i]["name"],
        item: data[i],
        disabled: isPos && data[i]["type"] === 2
      };
      temp = buildIterTree(data, data[i].id, isPos);
      if (temp.length > 0) {
        obj.children = temp;
      }
      result.push(obj);
    }
  }
  return result;
}
